<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="authorId">
        <el-input
          v-model="queryParams.authorId"
          placeholder="请输入"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="createdTime">
        <el-date-picker clearable
                        v-model="queryParams.createdTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" prop="updatedTime">
        <el-date-picker clearable
                        v-model="queryParams.updatedTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['empoly:article:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['empoly:article:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['empoly:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['empoly:article:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articlesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="文章标题" align="center" prop="title" />
      <el-table-column label="文章内容" align="center" prop="content" />
      <el-table-column label="作者ID" align="center" prop="authorId" />
      <el-table-column label="点赞数" align="center" prop="likes" />
      <el-table-column label="浏览数" align="center" prop="views" />
      <el-table-column label="是否置顶" align="center" prop="isPinned" >
        <template v-slot="scope">
          <el-tag :type="scope.row.isPinned ? 'success' : 'info'">
            {{ scope.row.isPinned ? '置顶' : '未置顶' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" align="center" prop="isRecommended">
        <template v-slot="scope">
          <el-tag :type="scope.row.isRecommended ? 'success' : 'info'">
            {{ scope.row.isRecommended ? '推荐' : '未推荐' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否删除（隐藏）" align="center" prop="isDeleted">
        <template v-slot="scope">
          <el-tag :type="scope.row.isDeleted ? 'danger' : 'info'">
            {{ scope.row.isDeleted ? '已删除（隐藏）' : '未删除（隐藏）' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="文章状态" align="center" prop="status" >
        <template v-slot="scope">
          <el-tag :type="getStatusTypeAndText(scope.row.status)">{{ getStatusTypeAndText(scope.row.status).text }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="文章标签" align="center" prop="tags" />

      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间" align="center" prop="updatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['empoly:article:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['empoly:article:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleHide(scope.row)"
            v-hasPermi="['empoly:article:hdie']"
          >隐藏</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="文章内容">
          <editor v-model="form.content" :min-height="300"/>
        </el-form-item>
        <el-form-item label="作者ID（暂未对接接口）" prop="authorId">
          <el-input v-model="form.authorId" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="是否置顶">
          <el-switch
            v-model="isPinnedComputed"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="是否推荐">
          <el-switch
            v-model="isRecommendedComputed"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="标签选择">
          <el-select v-model="setTagIds" multiple placeholder="请选择" @change="handleTagChange">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listArticles, getArticles, delArticles, addArticles, updateArticles, hideArticles} from "@/api/empoly/article";
import {listDictTag} from "@/api/empoly/dictTag";

export default {
  name: "Articles",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      articlesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        authorId: null,
        createdTime: null,
        updatedTime: null,
        status: null,
        isPinned: 0,
        isRecommended: 0,
        tags: null,
        tagIds: null,
      },
      options: [

      ],
      setTagIds: [

      ],
      // 表单参数
      form: {
        isPinned: 0, // 初始值设为0，表示不置顶
        isRecommended: 0, // 初始值设为0，表示不推荐
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "不能为空", trigger: "blur" }
        ],
      }
    };
  },
  computed: {
    // 使用计算属性来转换form.isPinned的值
    isPinnedComputed: {
      get() {
        return this.form.isPinned === 1;
      },
      set(value) {
        this.form.isPinned = value ? 1 : 0;
      },
    },
    isRecommendedComputed: {
      get() {
        return this.form.isRecommended === 1;
      },
      set(value) {
        this.form.isRecommended = value ? 1 : 0;
      },
    }
  },
  created() {
    this.getList();
  },
  methods: {
    handleTagChange(selectedValues) {
      // selectedValues 是一个数组，包含了所有已选项的值
      // 你可以在这里动态设置表单的其他值
      // 例如，根据选中的标签设置 otherFormValue
      this.form.tagIds = selectedValues.join(', '); // 假设你想将选中的标签值用逗号分隔后设置给 otherFormValue
    },

    /** 设置标签格式颜色*/
    getStatusTypeAndText(status) {
      const statusTypeMap = {
        'draft': { type: 'warning', text: '草稿' },
        'published': { type: 'success', text: '已发布' },
        'deleted': { type: 'danger', text: '已删除(隐藏)' },
        // ... 其他状态与类型和文本的映射
      };
      return statusTypeMap[status] || { type: '', text: status }; // 若无匹配状态，则返回原状态和空类型
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listArticles(this.queryParams).then(response => {
        this.articlesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        authorId: null,
        createdTime: null,
        updatedTime: null,
        status: null,
        isPinned: 0,
        isRecommended: 0,
        tags: null,
        tagIds: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文章资料";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      // 将原始的tagid映射到选择框上去.
      if(row.tagId !== null){
        this.setTagIds = row.tagId.split(",").map(Number)
      }
      listDictTag().then(res => {
        this.options = res.rows.map(item => ({
          value: item.id,
          label: item.name
        }));
      });
      getArticles(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateArticles(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArticles(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function() {
        return delArticles(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 隐藏按钮操作 */
    handleHide(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认隐藏编号为"' + ids + '"的数据项？').then(function() {
        return hideArticles(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("隐藏成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/articles/export', {
        ...this.queryParams
      }, `articles_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
